﻿/*
* 	Character Count Plugin - jQuery plugin
* 	Dynamic character count for text areas and input fields
*	written by Alen Grakalic	
*	http://cssglobe.com/post/7161/jquery-plugin-simplest-twitterlike-dynamic-character-count-for-textareas
*
*	Copyright (c) 2009 Alen Grakalic (http://cssglobe.com)
*	Dual licensed under the MIT (MIT-LICENSE.txt)
*	and GPL (GPL-LICENSE.txt) licenses.
*
*	Built for jQuery library
*	http://jquery.com
*
*/

(function ($) {

    $.fn.charCount = function (options) {
        // default configuration properties
        var defaults = {
            allowed: 255,
            warning: 1,
            css: 'counter',
            counterElement: 'span',
            cssWarning: 'warning',
            cssExceeded: 'exceeded',
            counterText: '还可输入'
        };
        
        if (options == null) {
            $(this).parent().next().find("." + defaults.css).html("还可输入255字");
            return;
        }

        var options = defaults; // $.extend(defaults, options);

        function calculate(obj) {
            var count = $(obj).val().length;
            var available = options.allowed - count;
            if (available <= options.warning && available >= 0) {
                $(obj).parent().next().find("." + options.css).addClass(options.cssWarning);
            } else {
                $(obj).parent().next().find("." + options.css).removeClass(options.cssWarning);
            }
            if (available < 0) {
                $(obj).parent().next().find("." + options.css).addClass(options.cssExceeded);
            } else {
                $(obj).parent().next().find("." + options.css).removeClass(options.cssExceeded);
            }

            if (available >= 0) {
                $(obj).parent().next().find("." + options.css).html(options.counterText + available + "字");
            } else {
                $(obj).parent().next().find("." + options.css).html("已超出" + Math.abs(available) + "字");
            }
        };

        this.each(function () {
            if ($(this).parent().next().find("." + options.css).length > 0) return;
            $(this).parent().next().append('<' + options.counterElement + ' class="' + options.css + '">' + options.counterText + '</' + options.counterElement + '>');
            calculate(this);
            $(this).keyup(function () { calculate(this) });
            $(this).change(function () { calculate(this) });
        });

    };

})(jQuery);